package com.superbytecode.cloud.rocketmq.scan;


import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ClassPathBeanDefinitionScanner;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.lang.NonNull;

import java.util.Set;

/**
 * All rights Reserved, Designed By www.super-master.com
 *
 * @ProjectName: beacon-cloud
 * @Package: com.superbytecode.cloud.rocketmq
 * @ClassName: ClassPathMQDefinitionScanner
 * @Description: []
 * <p> </p>
 * @Author: [Lance Ting]
 * @Date: 2024/11/1 23:16
 * @Version: V1.0
 * @Copyright: 2024 www.super-master.com Inc. All rights reserved.
 * TODO: 注意,本文件Lance Ting所作,如果转载或使用请标明具体出处!
 **/
public class ClassPathMQDefinitionScanner extends ClassPathBeanDefinitionScanner {

    public ClassPathMQDefinitionScanner(BeanDefinitionRegistry registry) {
        super(registry, false);
    }

    @Override
    protected boolean isCandidateComponent(AnnotatedBeanDefinition definition) {
        AnnotationMetadata metadata = definition.getMetadata();
        return metadata.isInterface() && metadata.isIndependent();
    }

    @Override
    protected Set<BeanDefinitionHolder> doScan(@NonNull String... packages) {
        Set<BeanDefinitionHolder> beanDefinitionHolders = super.doScan(packages);
        beanDefinitionHolders.forEach(definitionHolder -> {
            AbstractBeanDefinition beanDefinition = (AbstractBeanDefinition) definitionHolder.getBeanDefinition();
            String beanClassName = beanDefinition.getBeanClassName();
            beanDefinition.setBeanClass(MQFactoryBean.class);
            if (beanClassName == null) {
                return;
            }
            beanDefinition.getConstructorArgumentValues().addGenericArgumentValue(beanClassName);
            beanDefinition.setPrimary(true);
        });
        return beanDefinitionHolders;
    }
}